import random

from django.shortcuts import render
from django.views import View
from django_redis import get_redis_connection

from apps.verifications import constants
from libs.captcha.captcha import captcha
from django import http
import logging

from meiduo_mall import settings
from utils.response_code import RETCODE
from celery_tasks.sms.tasks import send_sms_code

from libs.yuntongxun.sms import CCP
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer

logger = logging.getLogger('django')


class ImageCodeView(View):
    """图形验证码"""

    def get(self, request, uuid):
        # 生成图片验证码
        text, image = captcha.generate_captcha()

        # 保存图片验证码
        redis_conn = get_redis_connection('code')
        redis_conn.setex('img_%s' % uuid, constants.IMAGE_CODE_REDIS_EXPIRES, text)

        # 响应图片验证码
        return http.HttpResponse(image, content_type='image/jpeg')


class SMSCodeView(View):
    def get(self, request, mobile):
        image_code_client = request.GET.get('image_code')
        # sms_code_client = request.POST.get('sms_code')
        uuid = request.GET.get('image_code_id')

        if not all([image_code_client, uuid]):
            return http.JsonResponse({'code': RETCODE.NECESSARYPARAMERR, 'errmsg': '缺少参数'})

        redis_conn = get_redis_connection('code')
        # sms_code_server = redis_conn.get('sms_%s' % mobile)
        # if sms_code_server is None:
        #     return render(request, 'register.html', {'sms_code_errmsg': '无效的短信验证码'})
        # if sms_code_client != sms_code_server.decode():
        #     return render(request, 'register.html', {'sms_code_errmsg': '输入短信验证码有误'})

        image_code_server = redis_conn.get('img_%s' % uuid)
        if image_code_server is None:
            return http.HttpResponseBadRequest('验证码已过期')

        try:
            redis_conn.delete('img:%s' % uuid)
        except Exception as e:
            logger.error(e)

        image_code_server = image_code_server.decode()
        if image_code_client.lower() != image_code_server.lower():
            return http.HttpResponse('验证码错误')

        sms_code = '%06d' % random.randint(0, 999999)
        logger.info(sms_code)
        send_flag = redis_conn.get('send_flag_%s' % mobile)

        if send_flag:
            return http.JsonResponse({'code': RETCODE.THROTTLINGERR, 'errmsg': '发送短信过于频繁'})

        pl = redis_conn.pipeline()

        pl.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        pl.setex('sms_flag_%s' % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)

        pl.execute()

        # redis_conn.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)

        # CCP().send_template_sms(mobile, [sms_code, constants.SMS_CODE_REDIS_EXPIRES], constants.SEND_SMS_TEMPLATE_ID)
        send_sms_code.delay(mobile, sms_code)

        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '发送成功'})

class SMSPWDView(View):

    def get(self, request):
        access_token = request.GET.get('access_token')
        serializer = Serializer(settings.SECRET_KEY)

        try:
            data = serializer.loads(access_token)
        except Exception:
            return http.JsonResponse({'code': RETCODE.NECESSARYPARAMERR, 'errmsg': '发生错误'})

        mobile = data.get('mobile')
        redis_conn = get_redis_connection('code')

        sms_code = '%06d' % random.randint(0, 999999)
        logger.info(sms_code)
        send_flag = redis_conn.get('send_flag_%s' % mobile)

        if send_flag:
            return http.JsonResponse({'code': RETCODE.THROTTLINGERR, 'errmsg': '发送短信过于频繁'})
        try:
            pl = redis_conn.pipeline()

            pl.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
            pl.setex('sms_flag_%s' % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)

            pl.execute()

            send_sms_code.delay(mobile, sms_code)
        except Exception:
            return http.JsonResponse({'code':RETCODE.NECESSARYPARAMERR, 'errmsg': '发生错误'})
        else:
            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '发送成功'})


# Create your views here.
